package com.zsc.roadsys.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zsc.roadsys.domain.PageDomain;
import com.zsc.roadsys.dto.UserDto;
import com.zsc.roadsys.entity.Role;
import com.zsc.roadsys.entity.User;
import com.zsc.roadsys.entity.UserRole;
import com.zsc.roadsys.mapper.UserMapper;
import com.zsc.roadsys.service.RoleService;
import com.zsc.roadsys.service.UserRoleService;
import com.zsc.roadsys.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author haoran
 */


@Service
public class UserServiceImpl  extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    RoleService roleService;

    @Autowired
    UserRoleService userRoleService;

    @Override
    public User getUserByUsername(String username) {
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.eq("username", username);
        User user = baseMapper.selectOne(userWrapper);
        Role role = roleService.getRoleById(userRoleService.getUrByUserId(user.getId()));
        user.setRole(role);
        return user;
    }

    @Override
    public User getUserById(Long id) {
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.eq("id", id);
        User user = baseMapper.selectOne(userWrapper);
        Role role = roleService.getRoleById(userRoleService.getUrByUserId(user.getId()));
        user.setRole(role);
        return user;
    }

    @Override
    public PageInfo<User> listUser(PageDomain pageDomain, User user) {
        PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize(),
                pageDomain.buildOrderStr());
        // 没有分页的SQL语句
        List<User> list = baseMapper.listUser(user);
        return new PageInfo<>(list);
    }

    @Override
    public boolean deleteUser(Long id) {
        if (baseMapper.deleteById(id) == 0) {
            return false;
        }
        userRoleService.deleteRoleByUserId(id);
        return true;
    }

    @Override
    public User updateUser(UserDto userDto) {
        //1、更新用户基本信息
        User user = baseMapper.selectById(userDto.getUserId());
        //密码进行md5加盐三次加密
//        Md5Hash md5Hash3 = new Md5Hash(userDto.getPassword(),"salt",3);
//        user.setPassword(md5Hash3.toHex());
        user.setEmail(userDto.getEmail());
        user.setPhone(userDto.getPhone());
        user.setEnable(userDto.getEnable());
        baseMapper.updateById(user);
        //2、删除原来的角色对应关系
        userRoleService.deleteRoleByUserId(userDto.getUserId());
        //3、插入新的关联
        UserRole userRole = UserRole.builder()
                                    .userId(userDto.getUserId())
                                    .roleId(userDto.getRoleId())
                                    .build();
        userRoleService.save(userRole);
        return this.getUserById(userDto.getUserId());
    }

    @Override
    public void updateStatusById(Long id, Long status) {
        User user = User.builder().id(id).enable(status).build();
        baseMapper.updateById(user);
    }

    @Override
    public void insertUser(User user) {
        //1、将用户基本信息插入用户表user
        baseMapper.insert(user);
        //2、插入对应的权限信息
        UserRole userRole = UserRole.builder().userId(user.getId()).roleId(2L).build();
        userRoleService.save(userRole);
    }

    @Override
    public String CrUserIdByTime() {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyyDHHmmss");
        String str = format.format(date);
        long uid = Long.parseLong(str);
        while (Long.parseLong(Long.toString(uid)) < 13){
            int num = new Random().nextInt(9);
            uid = (uid * 10) + num;
        }
        return Long.toString(uid);
    }
}
